/*
 * MIT License
 *
 * Copyright (c) 2024-2025 milkpotatoes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <iostream>
#include <vector>

#include "napi/native_api.h"
#include "runner_utils/napi_utils.h"

static napi_value RemoveFile(napi_env env, napi_callback_info info)
{
    utils::NapiCallbackInfo cbInfo(env, info);
    if (cbInfo.GetArgc() < 1 || !utils::IsString(env, cbInfo[0]))
    {
        utils::ThrowInvalidArg(env, "The first argument must be a string.");
        return nullptr;
    }
    std::string path = utils::GetValueStringUtf8(env, cbInfo[0]);
    if (path.empty())
    {
        utils::ThrowInvalidArg(env, "The first argument is an empty string.");
        return nullptr;
    }
    if (remove(path.c_str()) != 0)
    {
        napi_throw_error(env, "Remove file failed", path.c_str());
    }
    return nullptr;
}

static napi_value HelloWorld(napi_env, napi_callback_info)
{
    std::cout << "Hello World!" << std::endl;
    return nullptr;
}

static napi_value RunnerTest_Init(napi_env env, napi_value exports)
{
    std::vector<napi_property_descriptor> desc{
        {"removeFile", nullptr, RemoveFile, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"helloWorld", nullptr, HelloWorld, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, desc.size(), desc.data());
    return exports;
}

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = RunnerTest_Init,
    .nm_modname = "runner_test",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
